#include <Windows.h>
#include <fstream>
#include <string>
#include "cgraphics.hpp"

using namespace std;

#define ERROROK(msg) MessageBox(NULL, msg, "ERROR", MB_OK)

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

CGraphics CGr;

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
	HWND		hWnd;
	MSG			msg;
	WNDCLASS	WndClass;
	char *szAppName = "Elements";
	string		settings;
	int			hWndHeight, hWndWidth;

	WndClass.style			= CS_HREDRAW | CS_VREDRAW;
	WndClass.lpfnWndProc	= WndProc;
	WndClass.cbClsExtra		= 0;
	WndClass.cbWndExtra		= 0;
	WndClass.hInstance		= hInstance;
	WndClass.hIcon			= LoadIcon(NULL, IDI_APPLICATION);
	WndClass.hCursor		= LoadCursor(NULL, IDC_ARROW);
	WndClass.hbrBackground	= (HBRUSH) GetStockObject(WHITE_BRUSH);
	WndClass.lpszMenuName	= NULL;
	WndClass.lpszClassName	= szAppName;

	if(!RegisterClass(&WndClass))
	{
		ERROROK("Can't register Window Class!");

		return 0;
	}

	ifstream file_I ("element.settings", ios::binary);
	if(file_I.good () == true)
	{
		file_I	>>	settings;
		hWndWidth	=	(int(settings[0])-48)*1000 + (int(settings[1])-48)*100 + (int(settings[2])-48)*10 + (int(settings[3])-48);
		hWndHeight	=	(int(settings[5])-48)*1000 + (int(settings[6])-48)*100 + (int(settings[7])-48)*10 + (int(settings[8])-48);
	}
	else if(file_I.bad () == true)
	{
		ERROROK("Can't open 'element.settings'");
	}
	file_I.close ();

	hWnd = CreateWindow(szAppName,
						szAppName,
						WS_OVERLAPPEDWINDOW,
						CW_USEDEFAULT,
						CW_USEDEFAULT,
						hWndWidth,
						hWndHeight,
						NULL,
						NULL,
						hInstance,
						NULL);

	CGr.Init(hWnd);
	ShowWindow(hWnd, iCmdShow);
	UpdateWindow(hWnd);

	while(TRUE)
	{
		while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		if(msg.message == WM_QUIT)
		{
			return FALSE;
		}

		CGr.Render();
	}

	CGr.Clean();
	return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch(message)
	{
	case WM_KEYDOWN:
		{
			switch(wParam)
			{
			case VK_ESCAPE:
				{
					PostQuitMessage(0);

					return 0;
				}
			default:
				{
					return 0;
				}
			}
		}
	case WM_DESTROY:
		{
			PostQuitMessage(0);

			return 0;
		}
	}

	return DefWindowProc(hWnd, message, wParam, lParam);
}